package top.swimmer.provider.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import static top.swimmer.tools.io.IOUtils.close;

public class PinyinDictionary {

    private final static Logger LOGGER = Logger.getLogger(PinyinUtils.class.getSimpleName());

    private static final String dicLocation = "/dictionary/pinyin.dic";

    private Set<String> dictionary = new HashSet<String>();

    private static PinyinDictionary instance;

    private PinyinDictionary() {
        initialize();
    }

    private void initialize() {
        InputStream in = PinyinDictionary.class.getResourceAsStream(dicLocation);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        try {
            String line = null;
            long startPoint = System.currentTimeMillis();
            while (null != (line = reader.readLine())) {
                if (line.trim().length() > 0) {
                    dictionary.add(line);
                }
            }
            long endPoint = System.currentTimeMillis();
            LOGGER.info(String.format("Load pinyin from pinyin.dic, takes %s ms, size=%s", (endPoint - startPoint), dictionary.size()));
        } catch (Exception ex) {
            LOGGER.throwing("PinyinDictionary", "initialize", ex);
            throw new RuntimeException("read pinyin dic error.", ex);
        } finally {
            close(reader);
        }
    }

    public static PinyinDictionary getInstance() {
        if (instance == null) {
            synchronized (PinyinDictionary.class) {
                if (instance == null) {
                    instance = new PinyinDictionary();
                }
            }
        }
        return instance;
    }

    public boolean contains(String input) {
        return dictionary.contains(input);
    }
}
